import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { getDeptList, addDept, updateDept, deleteDept } from "@/api/system";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { hasAuths } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";

export function useDept() {
  const form = reactive({
    organizationName: "",
    isActive: null
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();
  const organizationList = ref([]);

  interface TreeNode {
    id: string;
    organizationId: string;
    organizationName: string;
    organizationPrincipalId: string | null;
    phoneNumber: string;
    email: string;
    sort: number;
    description: string;
    isActive: boolean;
    parentId: string | null;
    created: string;
    concurrencyStamp: string;
    children?: TreeNode[];
  }

  function buildTree(organizations: TreeNode[]): TreeNode[] {
    const map: { [key: string]: TreeNode } = {};
    const tree: TreeNode[] = [];

    organizations.forEach(organization => {
      map[organization.id] = organization;
      organization.children = [];
    });

    organizations.forEach(organization => {
      if (organization.parentId !== null && map[organization.parentId]) {
        map[organization.parentId].children.push(organization);
      } else {
        tree.push(organization);
      }
    });
    return tree;
  }

  const columns: TableColumnList = [
    {
      label: "组织名称",
      prop: "organizationName",
      width: 180,
      align: "left"
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "isActive",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          style={tagStyle.value(row.isActive === true ? 1 : 0)}
        >
          {row.isActive === true ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "created",
      formatter: ({ created }) => dayjs(created).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "备注",
      prop: "description",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation",
      hide: !hasAuths([
        "organization:add",
        "organization:id",
        "organization:delete:id"
      ])
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    const { data } = await getDeptList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    let newData = data;
    if (!isAllEmpty(form.organizationName)) {
      // 前端搜索组织机构名称
      newData = newData.filter(item =>
        item.organizationName.includes(form.organizationName)
      );
    }
    if (!isAllEmpty(form.isActive)) {
      // 前端搜索状态
      newData = newData.filter(item => item.isActive === form.isActive);
    }
    organizationList.value = newData;
    dataList.value = buildTree(newData); // 处理成树结构
    loading.value = false;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}组织机构`,
      props: {
        formInline: {
          higherDeptOptions: buildTree(cloneDeep(organizationList.value)),
          organizationId: row?.organizationId ?? null,
          parentId: row?.parentId ?? null,
          organizationName: row?.organizationName ?? null,
          organizationPrincipalId: row?.organizationPrincipalId ?? null,
          phoneNumber: row?.phoneNumber ?? null,
          email: row?.email ?? null,
          sort: row?.sort ?? 0,
          isActive: row?.isActive ?? true,
          description: row?.description ?? null,
          concurrencyStamp: row?.concurrencyStamp ?? null
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(
            `您${title}了组织机构名称为${curData.organizationName}的这条数据`,
            {
              type: "success"
            }
          );
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            curData.organizationPrincipalId =
              curData.organizationPrincipalId === ""
                ? null
                : curData.organizationPrincipalId;

            // 表单规则校验通过
            if (title === "新增") {
              await addDept(curData);
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              await updateDept(curData);
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  async function handleDelete(row) {
    await deleteDept(row);
    message(`删除成功`, {
      type: "success"
    });
    await onSearch();
  }

  onMounted(() => {
    console.log(useUserStoreHook());
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改组织机构 */
    openDialog,
    /** 删除组织机构 */
    handleDelete,
    handleSelectionChange
  };
}
